package com.ls.servlet.user;

import com.ls.pojo.User;
import com.ls.service.user.UserService;
import com.ls.service.user.UserServiceImpl;
import com.ls.util.constant.Constant;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

/**
 * @author 李朔
 * @version 1.0
 */
public class LoginServlet extends HttpServlet {

    //Servlet：控制层，调用业务层代码
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("LoginServlet--start....");
        //获取用户名和密码
        String userCode = req.getParameter("userCode");
        String userPassword = req.getParameter("userPassword");

        //和数据库中的密码进行对比，调用业务层；
        UserService userService=new UserServiceImpl();
        try {
            //这里就是查询登录的人
            User user = userService.login(userCode, userPassword);
            if(user!=null){
                //查有此人，可以登录
                //将用户的信息放到Session中；
                req.getSession().setAttribute(Constant.USER_SESSION,user);
                System.out.println("查有此人，进行登录");
                //登录成功之后，跳转到内部主页
                resp.sendRedirect(req.getContextPath()+"/jsp/frame.jsp");
            }else{
                //查无此人，无法登录
                //
                req.setAttribute("error","用户名或密码错误");
                req.getRequestDispatcher("login.jsp").forward(req,resp);

            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
